﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EasyTrader.Order
{
    using RowColList = List<EasyTrader.Order.PairRowCol>;
    using PriceOrderList = List<EasyTrader.Order.OrderInfo>;
    public partial class OrderFrm : System.Windows.Forms.Form
    {
#region Grid Cell View Members
        private SourceGrid.Cells.Views.Cell categoryView = null;
        private SourceGrid.Cells.Views.Cell resultView = null;
        private SourceGrid.Cells.Views.Cell headerView = null;
        private SourceGrid.Cells.Views.Cell priceView = null;
        private SourceGrid.Cells.Views.Cell buyView = null;
        private SourceGrid.Cells.Views.Cell sellView = null;
        private SourceGrid.Cells.Views.Cell centerView = null;
        private SourceGrid.Cells.Views.Cell midCenterView = null;
        private SourceGrid.Cells.Views.Cell normalView = null;
        private SourceGrid.Cells.Views.Cell orderBuyView = null;
        private SourceGrid.Cells.Views.Cell orderSellView = null;
        //private SourceGrid.Cells.Views.ColumnHeader viewColumnHeader = null;
        private SourceGrid.Cells.Views.Cell midCenterView2 = null;
        private SourceGrid.Cells.Views.Cell stopView = null;
#endregion
#region Order Variables
        private bool GridInit = false;
        RowColList m_OrderedCellList = new RowColList();
        private string AccountName = "";
        private string FutureCode = "";
        private int OrderType = 2;
        private int OrderCond = 0;
        private int LossTick = 0;
        private int ProfitTick = 0;
        public int centerRow = 13;
        public double CurVal = 0;
        public double accProfit = 0; // 누적이익
#endregion
        System.Timers.Timer CP6197Timer = new System.Timers.Timer();
        private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        delegate void TimerEventFiredDelegate();
        private TimerEventFiredDelegate DGCP6197Timer;
        IAsyncResult ARCP6197Timer;
        private void InitTimer()
        {
            timer.Interval = 1000;
            timer.Tick += new EventHandler(OnTimerTick);
            timer.Start();
        }

        private EasyTrader.Signal.TotalSignalManager m_TotalSignalManager = null;
        public EasyTrader.Signal.TotalSignalManager TotalSignalManager
        {
            get { return m_TotalSignalManager; }
            set { m_TotalSignalManager = value; }
        }

        // 타이머를 초기화 한다.
        private void InitCP6197Timer()
        {
            DGCP6197Timer = new OrderFrm.TimerEventFiredDelegate(CP6197TimerWork);
            CP6197Timer.Interval = 2000;
            CP6197Timer.Elapsed += new System.Timers.ElapsedEventHandler(OnCP6197TimerTick);
            CP6197Timer.Enabled = true;
        }

        private void OnCP6197TimerTick(object sender, EventArgs e)
        {
            ARCP6197Timer = BeginInvoke(DGCP6197Timer);
        }

        private void CP6197TimerWork()
        {
            if (m_OrderManager != null)
            {
                m_OrderManager.GetAccountBalance(AccountName);
            }
        }

        private void OnTimerTick(object sender, EventArgs e)
        {
            if (GridInit)
            {
                FillPriceColumn();
                FillJan();
                // 지정가에 의한 주문을 낸다.
                SendOrderByFixedOrder();
                ShowOrderPrice(AccountName);
                ShowStopPrice(AccountName);
                SendOrderByLossProfitTick();
                SendOrderByStopValue();
            }
            ShowServerMsg();
            UpdatePrice();
            ShowPriceState();
            if (m_OrderManager == null)
                return;
            OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(AccountName);
            if (curTable != null)
            {
                ShowOrderState(curTable);
                ShowFixedOrder(curTable);
            }
        }

        private void ShowFixedOrder(OrderTable curTable)
        {
            if (curTable == null || OrderType != 1)
                return;

            //ClearOrderedCell();
            double buyPrice = 0;
            double sellPrice = 0;
            int valRow = 0;
            if (curTable.FixedBuyOrderEnable == true)
            {
                ClearBuyOrderCell();
                buyPrice = curTable.FixedBuyOrderVal;
                valRow = FindValPos(buyPrice);
                // 값의 범위가 화면 안에 있을 경우
                if (valRow != 0)
                {
                    gridPrice[valRow, 5].Value = buyPrice.ToString("F2");
                    gridPrice[valRow, 5].View = stopView;
                }
            }

            if (curTable.FixedSellOrderEnable == true)
            {
                ClearSellOrderCell();
                sellPrice = curTable.FixedSellOrderVal;
                valRow = FindValPos(sellPrice);
                // 값의 범위가 화면 안에 있을 경우
                if (valRow != 0)
                {
                    gridPrice[valRow, 1].Value = sellPrice.ToString("F2");
                    gridPrice[valRow, 1].View = stopView;
                }
            }
        }

        // 지정가 주문이 있을 때 지정가 주문을 낸다.
        private void SendOrderByFixedOrder()
        {
            // 주문타입이 지정가가 아닐 때
            if (OrderType != 1)
            {
                return;
            }
            // 현재 계좌를 찾아 온다.
            if (m_OrderManager == null)
                return;
            //OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(AccountName);
            object a_Market = "1";
            object a_Account = AccountName;
            object a_ItemCode = FutureCode;
            object a_Amount = gridAmount[1, 0].Value;
            object a_OrderPrice = CurVal;
            object a_BuySell = 1;
            object a_OrderType = OrderType;
            object a_OrderCond = OrderCond;

            int tableCount = m_OrderManager.OrderDataSet.Tables.Count;
            for (int i = 0; i < tableCount; i++)
            {
                OrderTable curTable = (OrderTable)m_OrderManager.OrderDataSet.Tables[i];
                if (curTable != null && curTable.FixedBuyOrderEnable == true && CurVal == curTable.FixedBuyOrderVal)
                {
                    a_OrderPrice = CurVal;
                    a_BuySell = 2;
                    m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
                    curTable.ClearFixedBuyOrder();
                }

                if (curTable != null && curTable.FixedSellOrderEnable == true && CurVal == curTable.FixedSellOrderVal)
                {
                    a_OrderPrice = CurVal;
                    a_BuySell = 1;
                    m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
                    curTable.CleareFixedSellOrder();
                }
            }
        }

        public void SetFixedOrder(int a_BuySell, double a_Price)
        {
            // 현재 계좌를 찾아 온다.
            if (m_OrderManager == null)
                return;
            OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(AccountName);
            if (curTable == null)
                return;
            // 매도 설정일 때
            if (a_BuySell == 1)
            {
                curTable.FixedSellOrderVal = a_Price;
                curTable.FixedSellOrderEnable = true;
            }
            else if (a_BuySell == 2) // 매수 설정일 때
            {
                curTable.FixedBuyOrderEnable = true;
                curTable.FixedBuyOrderVal = a_Price;
            }
        }
        // 주문관리자 객체를 위한 참조
        private EasyTrader.Order.OrderManager m_OrderManager = null;
        public EasyTrader.Order.OrderManager OrderManager
        {
            get { return m_OrderManager; }
            set { m_OrderManager = value; }
        }

        private EasyTrader.ETDataSet m_CPDataSet = null;
        public EasyTrader.ETDataSet CPDataSet
        {
            get { return m_CPDataSet; }
            set { m_CPDataSet = value; }
        }
        public OrderFrm()
        {
            InitializeComponent();
            InitGridCellView();
            InitGrid();
            InitControl();
        }

        public void InitGridCellView()
        {
            DevAge.Drawing.RectangleBorder border = new DevAge.Drawing.RectangleBorder(new DevAge.Drawing.BorderLine(Color.DarkGreen), new DevAge.Drawing.BorderLine(Color.DarkGreen));
            //Category header
            categoryView = new SourceGrid.Cells.Views.Cell();
            categoryView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.RoyalBlue, Color.LightBlue, 0);
            categoryView.ForeColor = Color.FromKnownColor(KnownColor.ActiveCaptionText);
            categoryView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            categoryView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            categoryView.Font = new Font("굴림", 9, FontStyle.Bold);

            resultView = new SourceGrid.Cells.Views.Cell();
            //resultView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            resultView.BackColor = Color.LightGray;
            //resultView.ForeColor = Color.Black;
            resultView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            resultView.Border = border;
            resultView.Font = new Font("굴림", 9, FontStyle.Bold);

            headerView = new SourceGrid.Cells.Views.Cell();
            headerView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            headerView.ForeColor = Color.FromKnownColor(KnownColor.ActiveCaptionText);
            headerView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;
            headerView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            headerView.Font = new Font("굴림", 9, FontStyle.Bold);

            priceView = new SourceGrid.Cells.Views.Cell();
            //priceView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            //priceView.ForeColor = Color.FromKnownColor(KnownColor.ActiveCaptionText);
            priceView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            priceView.Border = border;
            priceView.Font = new Font("굴림", 9, FontStyle.Regular);

            buyView = new SourceGrid.Cells.Views.Cell();
            //priceView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            //priceView.ForeColor = Color.FromKnownColor(KnownColor.ActiveCaptionText);
            buyView.BackColor = Color.LightPink;
            buyView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            //priceView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            buyView.Font = new Font("굴림", 9, FontStyle.Regular);

            sellView = new SourceGrid.Cells.Views.Cell();
            //priceView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            //priceView.ForeColor = Color.FromKnownColor(KnownColor.ActiveCaptionText);
            sellView.BackColor = Color.LightSteelBlue;
            sellView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            //priceView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            sellView.Font = new Font("굴림", 9, FontStyle.Regular);

            centerView = new SourceGrid.Cells.Views.Cell();
            //priceView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            centerView.ForeColor = Color.Red;
            centerView.BackColor = Color.LightSteelBlue;
            centerView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            //priceView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            centerView.Font = new Font("굴림", 9, FontStyle.Regular);

            midCenterView = new SourceGrid.Cells.Views.Cell();
            //priceView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            midCenterView.ForeColor = Color.White;
            midCenterView.BackColor = Color.Blue;
            midCenterView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            //priceView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            midCenterView.Font = new Font("굴림", 9, FontStyle.Bold);

            midCenterView2 = new SourceGrid.Cells.Views.Cell();
            //priceView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            midCenterView2.ForeColor = Color.Black;
            midCenterView2.BackColor = Color.FromArgb(125, Color.Yellow);
            midCenterView2.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            //priceView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            midCenterView2.Font = new Font("굴림", 9, FontStyle.Bold);

            normalView = new SourceGrid.Cells.Views.Cell();
            normalView.ForeColor = Color.Black;
            normalView.BackColor = Color.White;
            normalView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            normalView.Font = new Font("굴림", 9, FontStyle.Regular);


            orderBuyView = new SourceGrid.Cells.Views.Cell();
            //priceView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            orderBuyView.ForeColor = Color.White;
            orderBuyView.BackColor = Color.Red;
            orderBuyView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            //priceView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            orderBuyView.Font = new Font("굴림", 9, FontStyle.Regular);

            orderSellView = new SourceGrid.Cells.Views.Cell();
            //priceView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            orderSellView.ForeColor = Color.White;
            orderSellView.BackColor = Color.Blue;
            orderSellView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            //priceView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            orderSellView.Font = new Font("굴림", 9, FontStyle.Regular);

            SourceGrid.Cells.Views.ColumnHeader viewColumnHeader = new SourceGrid.Cells.Views.ColumnHeader();
            DevAge.Drawing.VisualElements.ColumnHeader backHeader = new DevAge.Drawing.VisualElements.ColumnHeader();
            backHeader.BackColor = Color.ForestGreen;
            backHeader.Border = border;
            viewColumnHeader.Background = backHeader;
            viewColumnHeader.ForeColor = Color.White;
            viewColumnHeader.Font = new Font("굴림", 8, FontStyle.Bold);
            viewColumnHeader.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleCenter;


            stopView = new SourceGrid.Cells.Views.Cell();
            //priceView.Background = new DevAge.Drawing.VisualElements.BackgroundLinearGradient(Color.ForestGreen, Color.FloralWhite, 0);
            //priceView.ForeColor = Color.FromKnownColor(KnownColor.ActiveCaptionText);
            stopView.BackColor = Color.LightGreen;
            stopView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            //priceView.Border = DevAge.Drawing.RectangleBorder.NoBorder;
            stopView.Font = new Font("굴림", 9, FontStyle.Regular);
        }

        public OrderFrm(EasyTrader.Order.OrderManager a_OrderManager, EasyTrader.ETDataSet a_CPDataSet)
        {
            m_CPDataSet = a_CPDataSet;
            m_OrderManager = a_OrderManager;
            m_OrderManager.OrderFrame = this;
            InitializeComponent();
            InitGridCellView();
            InitGrid();
            InitTimer();
            nudCurValPos.Value = centerRow;
            nudCurValPos.Minimum = centerRow;
            nudCurValPos.Maximum = GlobalVar.ShowMaxPriceNumber;
        }

        private void ResetPriceGridCellView()
        {
            for (int r = 5; r < 5 + GlobalVar.ShowMaxPriceNumber; r++)
            {
                for (int c = 0; c < 7; c++)
                {
                    if (c == 2)
                    {
                        gridPrice[r, c].Value = "";
                    }
                    else if (c == 3)
                    {
                        gridPrice[r, c].Value = "";
                    }
                    else if (c == 4)
                    {
                        gridPrice[r, c].Value = "";
                    }
                }
            }

            for (int r = 5; r < 5 + GlobalVar.ShowMaxPriceNumber; r++)
            {
                for (int c = 0; c < 7; c++)
                {
                    if (c == 2)
                    {
                        if (r > (centerRow - 5) && r <= centerRow)
                        {
                            gridPrice[r, c].View = sellView;
                        }
                        else
                        {
                            gridPrice[r, c].View = normalView;
                        }
                    }
                    else if (c == 3)
                    {
                        if (r == centerRow)
                            gridPrice[r, c].View = midCenterView;
                        else
                            gridPrice[r, c].View = midCenterView2;
                    }
                    else if (c == 4)
                    {
                        if (r > centerRow && r <= centerRow + 5)
                        {
                            gridPrice[r, c].View = buyView;
                        }
                        else
                        {
                            gridPrice[r, c].View = normalView;
                        }
                    }
                    else
                    {
                        gridPrice[r, c].View = normalView;
                    }
                }
            }
        }

        private void InitGrid()
        {
            // 이벤트 핸들러를 생성하고 등록한다.
            CellClickEvent clickController = new CellClickEvent();
            clickController.OrderFrm = this;
            clickController.OrderManager = m_OrderManager;
            clickController.PriceGrid = gridPrice;
            clickController.AmountGrid = gridAmount;

            CellDoubleClickEvent doubleClickController = new CellDoubleClickEvent();
            doubleClickController.PriceGrid = gridPrice;
            doubleClickController.OrderManager = m_OrderManager;
            doubleClickController.AmountGrid = gridAmount;
            doubleClickController.OrderFrm = this;

            AmountCellDoubleClickEvent AmountDoubleClickController = new AmountCellDoubleClickEvent();
            doubleClickController.PriceGrid = gridPrice;
            doubleClickController.OrderManager = m_OrderManager;
            doubleClickController.AmountGrid = gridAmount;
            doubleClickController.OrderFrm = this;


            gridState.BorderStyle = BorderStyle.FixedSingle;

            gridState.ColumnsCount = 9;
            gridState.FixedRows = 1;
            gridState.Rows.Insert(0);

            gridState[0, 0] = new SourceGrid.Cells.ColumnHeader("종류");
            gridState[0, 1] = new SourceGrid.Cells.ColumnHeader("잔량");
            gridState[0, 2] = new SourceGrid.Cells.ColumnHeader("주문");
            gridState[0, 3] = new SourceGrid.Cells.ColumnHeader("Stop");
            gridState[0, 4] = new SourceGrid.Cells.ColumnHeader("기준가");
            gridState[0, 5] = new SourceGrid.Cells.ColumnHeader("최대");
            gridState[0, 6] = new SourceGrid.Cells.ColumnHeader("청가");
            gridState[0, 7] = new SourceGrid.Cells.ColumnHeader("평균단가");
            gridState[0, 8] = new SourceGrid.Cells.ColumnHeader("평가손익");

            for (int i = 0; i < 9; i++)
                gridState[0, i].View = categoryView;

            for (int r = 1; r <= 2; r++)
            {
                gridState.Rows.Insert(r);
                if (r == 1)
                    gridState[r, 0] = new SourceGrid.Cells.Cell("매수");
                else if (r == 2)
                    gridState[r, 0] = new SourceGrid.Cells.Cell("매도");
                else
                    gridState[r, 0] = new SourceGrid.Cells.Cell();
                gridState[r, 1] = new SourceGrid.Cells.Cell();
                gridState[r, 2] = new SourceGrid.Cells.Cell();
                gridState[r, 3] = new SourceGrid.Cells.Cell();
                gridState[r, 4] = new SourceGrid.Cells.Cell("000.00");
                gridState[r, 5] = new SourceGrid.Cells.Cell();
                gridState[r, 6] = new SourceGrid.Cells.Cell();
                gridState[r, 7] = new SourceGrid.Cells.Cell();
                gridState[r, 8] = new SourceGrid.Cells.Cell();
                //gridState[r, 8].AddController(clickController);
                //gridState[r, 8].AddController(doubleClickController);
            }

            gridState.AutoSizeCells();


            gridPrice.BorderStyle = BorderStyle.FixedSingle;



            //DevAge.Drawing.VisualElements.ColumnHeader flatHeader = new DevAge.Drawing.VisualElements.ColumnHeader();

            gridPrice.ColumnsCount = 7;
            gridPrice.FixedRows = 5;
            gridPrice.Rows.Insert(0);

            gridPrice[0, 0] = new SourceGrid.Cells.Cell("매도");
            gridPrice[0, 0].SetSpan(1, 3);
            gridPrice[0, 0].View = categoryView;
            gridPrice[0, 3] = new SourceGrid.Cells.Cell("호가  ");
            gridPrice[0, 3].SetSpan(1, 1);
            gridPrice[0, 3].View = categoryView;
            gridPrice[0, 4] = new SourceGrid.Cells.Cell("매수");
            gridPrice[0, 4].SetSpan(1, 3);
            gridPrice[0, 4].View = categoryView;

            gridPrice.Rows.Insert(1);

            gridPrice[1, 0] = new SourceGrid.Cells.Cell("Stop");
            gridPrice[1, 1] = new SourceGrid.Cells.Cell("주문");
            gridPrice[1, 2] = new SourceGrid.Cells.Cell("잔량");
            //gridPrice[1, 3] = new SourceGrid.Cells.ColumnHeader("호가");
            gridPrice[1, 4] = new SourceGrid.Cells.Cell("잔량");
            gridPrice[1, 5] = new SourceGrid.Cells.Cell("주문");
            gridPrice[1, 6] = new SourceGrid.Cells.Cell("Stop");

            gridPrice[1, 0].View = headerView;
            gridPrice[1, 1].View = headerView;
            gridPrice[1, 2].View = headerView;
            //gridPrice[1, 3].View = viewColumnHeader;
            gridPrice[1, 4].View = headerView;
            gridPrice[1, 5].View = headerView;
            gridPrice[1, 6].View = headerView;

            gridPrice.Rows.Insert(2);
            gridPrice[2, 0] = new SourceGrid.Cells.Cell("취소");
            gridPrice[2, 0].AddController(clickController);
            gridPrice[2, 1] = new SourceGrid.Cells.Cell("취소");
            gridPrice[2, 2] = new SourceGrid.Cells.Cell("0");
            gridPrice[2, 3] = new SourceGrid.Cells.Cell("0");
            gridPrice[2, 4] = new SourceGrid.Cells.Cell("0");
            gridPrice[2, 5] = new SourceGrid.Cells.Cell("취소");
            gridPrice[2, 6] = new SourceGrid.Cells.Cell("취소");
            gridPrice[2, 6].AddController(clickController);

            gridPrice[2, 0].View = resultView;
            gridPrice[2, 1].View = resultView;
            gridPrice[2, 2].View = sellView;
            gridPrice[2, 3].View = centerView;
            gridPrice[2, 4].View = buyView;
            gridPrice[2, 5].View = resultView;
            gridPrice[2, 6].View = resultView;

            gridPrice.Rows.Insert(3);
            gridPrice[3, 0] = new SourceGrid.Cells.Cell("0");
            gridPrice[3, 1] = new SourceGrid.Cells.Cell("0");
            gridPrice[3, 2] = new SourceGrid.Cells.Cell("0");
            gridPrice[3, 3] = new SourceGrid.Cells.Cell("0");
            gridPrice[3, 4] = new SourceGrid.Cells.Cell("0");
            gridPrice[3, 5] = new SourceGrid.Cells.Cell("0");
            gridPrice[3, 6] = new SourceGrid.Cells.Cell("0");

            gridPrice[3, 0].View = normalView;
            gridPrice[3, 1].View = normalView;
            gridPrice[3, 2].View = sellView;
            gridPrice[3, 3].View = centerView;
            gridPrice[3, 4].View = buyView;
            gridPrice[3, 5].View = normalView;
            gridPrice[3, 6].View = normalView;
            //gridPrice.AutoSizeCells();


            gridPrice.Rows.Insert(4);
            gridPrice[4, 0] = new SourceGrid.Cells.Cell("0");
            gridPrice[4, 1] = new SourceGrid.Cells.Cell("0");
            gridPrice[4, 2] = new SourceGrid.Cells.Cell("0");
            gridPrice[4, 3] = new SourceGrid.Cells.Cell("");
            gridPrice[4, 4] = new SourceGrid.Cells.Cell("0");
            gridPrice[4, 5] = new SourceGrid.Cells.Cell("0");
            gridPrice[4, 6] = new SourceGrid.Cells.Cell("0");

            gridPrice[4, 0].View = normalView;
            gridPrice[4, 1].View = normalView;
            gridPrice[4, 2].View = normalView;
            gridPrice[4, 3].View = normalView;
            gridPrice[4, 4].View = normalView;
            gridPrice[4, 5].View = normalView;
            gridPrice[4, 6].View = normalView;

            for (int r = 5; r < 5 + GlobalVar.ShowMaxPriceNumber; r++)
            {
                gridPrice.Rows.Insert(r);

                for (int c = 0; c < 7; c++)
                {
                    if (c == 2)
                    {
                        if (r > (centerRow - 5) && r <= centerRow)
                        {
                            gridPrice[r, c] = new SourceGrid.Cells.Cell("");
                            gridPrice[r, c].View = sellView;
                        }
                        else
                        {
                            gridPrice[r, c] = new SourceGrid.Cells.Cell("");
                            gridPrice[r, c].View = normalView;
                        }
                    }
                    else if (c == 3)
                    {
                        gridPrice[r, c] = new SourceGrid.Cells.Cell("000.00");
                        if (r == centerRow)
                            gridPrice[r, c].View = midCenterView;
                        else
                            gridPrice[r, c].View = midCenterView2;
                    }
                    else if (c == 4)
                    {
                        if (r > centerRow && r <= centerRow + 5)
                        {
                            gridPrice[r, c] = new SourceGrid.Cells.Cell("");
                            gridPrice[r, c].View = buyView;
                        }
                        else
                        {
                            gridPrice[r, c] = new SourceGrid.Cells.Cell("");
                            gridPrice[r, c].View = normalView;
                        }
                    }
                    else
                    {
                        gridPrice[r, c] = new SourceGrid.Cells.Cell("");
                        gridPrice[r, c].View = normalView;
                        gridPrice[r, c].AddController(doubleClickController);
                    }
                }
            }

            

            gridAmount.BorderStyle = BorderStyle.FixedSingle;

            gridAmount.ColumnsCount = 1;
            gridAmount.FixedRows = 1;
            for (int p = 0; p < 13; p++)
                gridAmount.Rows.Insert(p);

            gridAmount[0, 0] = new SourceGrid.Cells.ColumnHeader("수량");
            gridAmount[0, 0].View = categoryView;
            gridAmount[1, 0] = new SourceGrid.Cells.Cell("1");
            gridAmount[2, 0] = new SourceGrid.Cells.Cell("0");
            gridAmount[2, 0].View = midCenterView2;
            gridAmount[2, 0].AddController(clickController);

            gridAmount[3, 0] = new SourceGrid.Cells.Cell("1");
            gridAmount[4, 0] = new SourceGrid.Cells.Cell("2");
            gridAmount[5, 0] = new SourceGrid.Cells.Cell("3");
            gridAmount[6, 0] = new SourceGrid.Cells.Cell("4");
            gridAmount[7, 0] = new SourceGrid.Cells.Cell("5");
            gridAmount[8, 0] = new SourceGrid.Cells.Cell("6");
            gridAmount[9, 0] = new SourceGrid.Cells.Cell("7");
            gridAmount[10, 0] = new SourceGrid.Cells.Cell("8");
            gridAmount[11, 0] = new SourceGrid.Cells.Cell("9");
            gridAmount[12, 0] = new SourceGrid.Cells.Cell("10");

            gridAmount[1, 0].View = normalView;
            for (int k = 3; k < 13; k++)
            {
                gridAmount[k, 0].View = normalView;
                gridAmount[k, 0].AddController(clickController);
            }
            gridAmount.AutoSizeCells();

            GridInit = true;
        }

        private void ShowPriceState()
        {
            txtTotalProfit.Text = accProfit.ToString("F2");
        }
        private void ShowServerMsg()
        {
            txtServerMsg.Text = GlobalVar.ServerOrderMsg;
        }

        public void ShowOrderState(OrderTable curTable)
        {
            string stateMsg = "주문상태 : " + GlobalVar.OrderState;
            txtOrderState.Text = stateMsg;

            if (curTable == null)
                return;
            txtTotalProfit.Text = "전체 수익 : " + curTable.TotalProfit.ToString("F2") + " 만원";
            txtCurProfit.Text = "현재 수익 : " + curTable.CurProfit.ToString("F2") + " 만원";

            int rowCount = curTable.Rows.Count;
            if (rowCount == 0)
                return;

            DataRow curRow = curTable.Rows[rowCount - 1];
            object remain = curRow["잔고"];
            object remainCode = curRow["잔고구분코드"];
            
            // 현재 테이블에서 주문 정보 목록을 가져온다.
            PriceOrderList orderList = curTable.OrderList;
            int orderCount = orderList.Count;
            if (orderCount == 0)
                return;

            string strRemainCode = remainCode.ToString();
            if (strRemainCode == "")
                remainCode = 0;
            else
            {
                remainCode = Convert.ToInt32(remainCode);
            }

            OrderInfo curOrder = orderList[orderCount - 1];
            double orderPrice = curOrder.Price;
            FillOrderState(curOrder, curTable, Convert.ToInt32(remainCode));
        }

        public void UpdatePrice()
        {
            if (m_CPDataSet == null)
                return;
            EasyTrader.FutureCurOnlyTable curTable = m_CPDataSet.GetFutureCurOnlyTable();
            if (curTable == null)
                return;
            DataRow curRow = curTable.GetLastRow();
            if (curRow == null)
                return;
            if (curRow["종가"] == DBNull.Value)
                return;

            textBoxClose.Text = Convert.ToDouble(curRow["종가"]).ToString("F2");
            textBoxOpen.Text = Convert.ToDouble(curRow["시가"]).ToString("F2");
            textBoxLow.Text = Convert.ToDouble(curRow["저가"]).ToString("F2");
            textBoxHigh.Text = Convert.ToDouble(curRow["고가"]).ToString("F2");
        }

        private void OrderFrm_Load(object sender, EventArgs e)
        {
            if (m_OrderManager != null)
            {
                m_OrderManager.InitOrder();
                FillAccount();
                FillFutureCode();
                InitOrderType();
                InitOrderCond();
                ShowOrderPrice(AccountName);
                ShowStopPrice(AccountName);
                //InitCP6197Timer();
            }
        }

        private void InitControl()
        {
            int lossTicks = (int)(GlobalVar.AutoLossStopPrice / 0.05);
            int profitTicks = (int)(GlobalVar.AutoProfitStopPrice / 0.05);
            nudLossTicks.Value = (int)lossTicks;
            nudProfitTicks.Value = (int)profitTicks;
        }

        private void InitOrderType()
        {
            if (GlobalVar.OrderType == 1)
            {
                comboOrderType.SelectedIndex = 0;
                OrderType = 1;
            }
            else if (GlobalVar.OrderType == 2)
            {
                comboOrderType.SelectedIndex = 1;
                OrderType = 2;
            }
            else if (GlobalVar.OrderType == 3)
            {
                comboOrderType.SelectedIndex = 2;
                OrderType = 3;
            }
            else if (GlobalVar.OrderType == 4)
            {
                comboOrderType.SelectedIndex = 3;
                OrderType = 4;
            }
            else
            {
                comboOrderType.SelectedIndex = 1;
                OrderType = 2;
            }
            if (OrderType == 1)
            {
                btnCancelFixedOrder.Enabled = true;
            }
            else
            {
                btnCancelFixedOrder.Enabled = false;
            }
        }

        private void InitOrderCond()
        {
            comboOrderCond.SelectedIndex = GlobalVar.OrderCond;
            OrderCond = GlobalVar.OrderCond;
        }

        private void FillAccount()
        {
            if (m_OrderManager == null)
                return;

            //계좌번호 얻기 
            Array arAccount = m_OrderManager.GetAccountArray();           
            for (int i = 0; i < arAccount.GetLength(0); i++)
            {
                // 계좌번호로 테이블을 만든다.
                string accountNumber = arAccount.GetValue(i).ToString();
                comboAccount.Items.Add(accountNumber);
            }
            comboAccount.SelectedIndex = 0;
        }

        private void FillFutureCode()
        {
            textBoxFutureCode.Text = m_OrderManager.GetCurFutureCode();
            FutureCode = m_OrderManager.GetCurFutureCode();
        }

        public class CellClickEvent : SourceGrid.Cells.Controllers.ControllerBase
        {
            private EasyTrader.Order.OrderFrm m_OrderFrm = null;
            public EasyTrader.Order.OrderFrm OrderFrm
            {
                get { return m_OrderFrm; }
                set { m_OrderFrm = value; }
            }

            private SourceGrid.Grid m_AmountGrid = null;
            public SourceGrid.Grid AmountGrid
            {
                get { return m_AmountGrid; }
                set { m_AmountGrid = value; }
            }

            private SourceGrid.Grid m_PriceGrid = null;
            public SourceGrid.Grid PriceGrid
            {
                get { return m_PriceGrid; }
                set { m_PriceGrid = value; }
            }
            private EasyTrader.Order.OrderManager m_OrderManager = null;
            public EasyTrader.Order.OrderManager OrderManager
            {
                get { return m_OrderManager; }
                set { m_OrderManager = value; }
            }

            public override void OnClick(SourceGrid.CellContext sender, EventArgs e)
            {
                base.OnClick(sender, e);
                SourceGrid.Cells.Cell curCell = (SourceGrid.Cells.Cell)sender.Cell;
                //MessageBox.Show(sender.Grid, curCell.Column.Index.ToString() + curCell.Row.Index.ToString());
                m_AmountGrid = (SourceGrid.Grid)sender.Grid;
                string value = curCell.Value.ToString();
                if (value == "")
                    return;
                m_AmountGrid[1, 0].Value = value;
                /*
                OrderTable curTable = (OrderTable)m_OrderManager.OrderDataSet.Tables[m_OrderFrm.AccountName];
                if (curTable != null && curTable.StopEnabled == true)
                {
                    m_OrderFrm.ClearStopCell();
                    m_OrderManager.ClearStopInfo(m_OrderFrm.AccountName);
                }*/
            }
        }

        public class CellDoubleClickEvent : SourceGrid.Cells.Controllers.ControllerBase
        {
            private EasyTrader.Order.OrderFrm m_OrderFrm = null;
            public EasyTrader.Order.OrderFrm OrderFrm
            {
                get { return m_OrderFrm; }
                set { m_OrderFrm = value; }
            }

            private SourceGrid.Grid m_AmountGrid = null;
            public SourceGrid.Grid AmountGrid
            {
                get { return m_AmountGrid; }
                set { m_AmountGrid = value; }
            }

            private SourceGrid.Grid m_PriceGrid = null;
	        public SourceGrid.Grid PriceGrid
	        {
		        get { return m_PriceGrid; }
		        set { m_PriceGrid = value; }
	        }
            private EasyTrader.Order.OrderManager m_OrderManager = null;
	        public EasyTrader.Order.OrderManager OrderManager
	        {
		        get { return m_OrderManager; }
		        set { m_OrderManager = value; }
	        }

            public override void OnDoubleClick(SourceGrid.CellContext sender, EventArgs e)
            {
                base.OnDoubleClick(sender, e);
                SourceGrid.Cells.Cell curCell = (SourceGrid.Cells.Cell)sender.Cell;
                //MessageBox.Show(sender.Grid, curCell.Column.Index.ToString() + curCell.Row.Index.ToString());
                if (m_OrderManager == null)
                    return;

                SourceGrid.Grid gridPrice = (SourceGrid.Grid)sender.Grid;
                string closeVal = gridPrice[m_OrderFrm.centerRow, 3].Value.ToString();
                if (closeVal == "")
                    return;

                double curVal = Convert.ToDouble(closeVal) + (m_OrderFrm.centerRow - curCell.Row.Index) * 0.05;
                //gridPrice[curCell.Row.Index, curCell.Column.Index].Value = curVal.ToString("F2");
                if (m_AmountGrid != null && m_OrderManager != null && m_OrderFrm != null)
                {
                    object a_Market = "1";
                    object a_Account = m_OrderFrm.AccountName;
                    object a_ItemCode = m_OrderFrm.FutureCode;
                    object a_Amount = m_AmountGrid[1, 0].Value;
                    object a_OrderPrice = curVal;
                    object a_BuySell;
                    object a_OrderType = m_OrderFrm.OrderType;
                    object a_OrderCond = m_OrderFrm.OrderCond;
                    if (curCell.Column.Index == 1)
                    {
                        if (GlobalVar.AutoOrder == true)
                        {
                            System.Windows.Forms.MessageBox.Show(GlobalVar.ManualOrderWarnMsg);
                            return;
                        }
                        //m_OrderFrm.ClearOrderedCell();
                        m_OrderFrm.ClearSellOrderCell();
                        a_BuySell = 1; // 매도
                        // 주문유형이 시장가 일 때
                        if (m_OrderFrm.OrderType == 2)
                        {
                            a_OrderPrice = 0;
                            m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
                        }
                        else if (m_OrderFrm.OrderType == 1) // 지정가 일 때
                        {
                            string strFixVal = gridPrice[curCell.Row.Index, 3].Value.ToString();
                            if (strFixVal != "")
                            {
                                double fixVal = Convert.ToDouble(strFixVal);
                                m_OrderFrm.SetFixedOrder(Convert.ToInt32(a_BuySell), fixVal);
                            }
                        }
                        else // 주문 유형이 시장가가 아닐 때
                        {
                            m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
                        }
                        gridPrice[curCell.Row.Index, curCell.Column.Index].Value = curVal.ToString("F2");

                        string orderInfo = "주문창 매도 주문 정보 ->";
                        orderInfo += "주문계좌 : " + a_Account + ", ";
                        orderInfo += "주문시간 : " + GlobalVar.TimeToInt().ToString() + ", ";
                        orderInfo += "주문유형 : " + a_BuySell.ToString() + ", ";
                        orderInfo += "주문가격 : " + a_OrderPrice.ToString() + ", ";
                        orderInfo += "주문수량 : " + a_Amount.ToString();
                        GlobalVar.WriteLog(orderInfo);
                    }
                    else if (curCell.Column.Index == 5)
                    {
                        if (GlobalVar.AutoOrder == true)
                        {
                            System.Windows.Forms.MessageBox.Show(GlobalVar.ManualOrderWarnMsg);
                            return;
                        }
                        //m_OrderFrm.ClearOrderedCell();
                        m_OrderFrm.ClearBuyOrderCell();
                        a_BuySell = 2; // 매수
                        // 주문유형이 시장가 일 때
                        if (m_OrderFrm.OrderType == 2)
                        {
                            a_OrderPrice = 0;
                            m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
                        }
                        else if (m_OrderFrm.OrderType == 1) // 지정가 일 때
                        {
                            string strFixVal = gridPrice[curCell.Row.Index, 3].Value.ToString();
                            if (strFixVal != "")
                            {
                                double fixVal = Convert.ToDouble(strFixVal);
                                m_OrderFrm.SetFixedOrder(Convert.ToInt32(a_BuySell), fixVal);
                            }
                        }
                        else // 주문 유형이 시장가가 아닐 때
                        {
                            m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
                        }
                        gridPrice[curCell.Row.Index, curCell.Column.Index].Value = curVal.ToString("F2");
                        string orderInfo = "주문창 매수 주문 정보 ->";
                        orderInfo += "주문계좌 : " + a_Account + ", ";
                        orderInfo += "주문시간 : " + GlobalVar.TimeToInt().ToString() + ", ";
                        orderInfo += "주문유형 : " + a_BuySell.ToString() + ", ";
                        orderInfo += "주문가격 : " + a_OrderPrice.ToString() + ", ";
                        orderInfo += "주문수량 : " + a_Amount.ToString();
                        GlobalVar.WriteLog(orderInfo);
                    }
                    else if (curCell.Column.Index == 0 || curCell.Column.Index == 6) // 스탑 주문 설정
                    {
                        OrderTable curTable = (OrderTable)m_OrderManager.OrderDataSet.Tables[m_OrderFrm.AccountName];
                        int rowCount = curTable.Rows.Count;
                        if (rowCount > 0)
                        {
                            DataRow lastRow = curTable.Rows[rowCount - 1];
                            int liquidAmount = Convert.ToInt32(lastRow["청산가능수량"]);
                            string remainCode = lastRow["잔고구분코드"].ToString();
                            // 청산 가능 수량이 0보다 클 때
                            if (remainCode != "" && (remainCode == "1" || remainCode == "2") && liquidAmount > 0)
                            {
                                // 매도 잔고가 남아 있는 상태임
                                if (remainCode == "1")
                                {
                                    if (curCell.Column.Index == 0) // 매도 스탑 설정
                                    {
                                        m_OrderFrm.ClearStopCell();
                                        m_OrderManager.SetStopInfo(m_OrderFrm.AccountName, 2, curVal);
                                        //gridPrice[curCell.Row.Index, curCell.Column.Index].Value = curVal.ToString("F2");
                                        m_OrderFrm.ShowStopPrice(m_OrderFrm.AccountName);
                                    }
                                }
                                else if (remainCode == "2") // 매수 잔고가 남아 있는 상태임
                                {
                                    if (curCell.Column.Index == 6) // 매수 스탑 설정
                                    {
                                        m_OrderFrm.ClearStopCell();
                                        m_OrderManager.SetStopInfo(m_OrderFrm.AccountName, 1, curVal);
                                        //gridPrice[curCell.Row.Index, curCell.Column.Index].Value = curVal.ToString("F2");
                                        m_OrderFrm.ShowStopPrice(m_OrderFrm.AccountName);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }


        public class AmountCellDoubleClickEvent : SourceGrid.Cells.Controllers.ControllerBase
        {
            private EasyTrader.Order.OrderFrm m_OrderFrm = null;
            public EasyTrader.Order.OrderFrm OrderFrm
            {
                get { return m_OrderFrm; }
                set { m_OrderFrm = value; }
            }

            private SourceGrid.Grid m_AmountGrid = null;
            public SourceGrid.Grid AmountGrid
            {
                get { return m_AmountGrid; }
                set { m_AmountGrid = value; }
            }

            private SourceGrid.Grid m_PriceGrid = null;
            public SourceGrid.Grid PriceGrid
            {
                get { return m_PriceGrid; }
                set { m_PriceGrid = value; }
            }
            private EasyTrader.Order.OrderManager m_OrderManager = null;
            public EasyTrader.Order.OrderManager OrderManager
            {
                get { return m_OrderManager; }
                set { m_OrderManager = value; }
            }

            public override void OnDoubleClick(SourceGrid.CellContext sender, EventArgs e)
            {
                base.OnDoubleClick(sender, e);
                SourceGrid.Cells.Cell curCell = (SourceGrid.Cells.Cell)sender.Cell;
                //MessageBox.Show(sender.Grid, curCell.Column.Index.ToString() + curCell.Row.Index.ToString());
                if (m_OrderManager == null)
                    return;

                SourceGrid.Grid gridPrice = (SourceGrid.Grid)sender.Grid;
                
            }
        }

        private void FillPriceColumn()
        {
            if (m_CPDataSet == null)
                return;
            EasyTrader.FutureCurOnlyTable curTable = m_CPDataSet.GetFutureCurOnlyTable();
            if (curTable == null)
                return;
            DataRow curRow = curTable.GetLastRow();
            if (curRow == null)
                return;

            object closeVal = curRow["종가"];
            if (closeVal == DBNull.Value)
                return;

            // 여기서 항상 현재 가격을 갱신해 준다.
            CurVal = Convert.ToDouble(closeVal);
            if (closeVal != DBNull.Value && Convert.ToDouble(closeVal) != 0)
            {
                for (int r = 5; r < 5 + GlobalVar.ShowMaxPriceNumber; r++)
                {
                    double curVal = Convert.ToDouble(closeVal) + (centerRow - r) * 0.05;
                    if (gridPrice[r, 3] != null)
                        gridPrice[r, 3].Value = curVal.ToString("F2");
                }
            }
        } // FillPriceColumn

        /*
        private void FillOrderBuy(object a_Price, object a_Amount, object a_Remain)
        {
            gridPrice[3, 5].Value = Convert.ToDouble(a_Price).ToString("F2");
            gridPrice[4, 5].Value = a_Amount;
            gridPrice[4, 4].Value = a_Remain;
        }

        private void FillOrderSell(object a_Price, object a_Amount, object a_Remain)
        {
            gridPrice[3, 1].Value = Convert.ToDouble(a_Price).ToString("F2");
            gridPrice[4, 1].Value = a_Amount;
            gridPrice[4, 2].Value = a_Remain;
        }*/

        private void FillOrderBuy(OrderInfo a_CurOrder, OrderTable a_CurTable, int a_Remain)
        {
            gridPrice[3, 5].Value = a_CurOrder.Price.ToString("F2");
            gridPrice[4, 5].Value = a_CurOrder.Amount;
            gridPrice[4, 4].Value = a_Remain;
            
        }

        private void FillOrderState(OrderInfo a_CurOrder, OrderTable a_CurTable, int a_RemainCode)
        {
            if (a_RemainCode == 2)
            {
                gridState[1, 2].Value = a_CurOrder.Amount;
                gridState[1, 6].Value = a_CurOrder.LiquidAmount;
                gridState[1, 7].Value = a_CurOrder.Price;
                if (a_CurTable != null)
                {
                    gridState[1, 8].Value = a_CurTable.TotalProfit;
                }
            }
            else if (a_RemainCode == 1)
            {
                gridState[2, 2].Value = a_CurOrder.Amount;
                gridState[2, 6].Value = a_CurOrder.LiquidAmount;
                gridState[2, 7].Value = a_CurOrder.Price;
                if (a_CurTable != null)
                {
                    gridState[2, 8].Value = a_CurTable.TotalProfit;
                }
            }
            else
            {
                gridState[1, 2].Value = 0;
                gridState[1, 6].Value = 0;
                gridState[1, 7].Value = 0.00;
                
                gridState[1, 8].Value = a_CurTable.TotalProfit;
                

                gridState[2, 2].Value = 0;
                gridState[2, 6].Value = 0;
                gridState[2, 7].Value = 0.00;
                
                gridState[2, 8].Value = a_CurTable.TotalProfit;
                
            }
        }

        private void ResetOrderSell()
        {
            gridPrice[3, 1].Value = 0.00;
            gridPrice[4, 1].Value = 0;
            gridPrice[4, 2].Value = 0;

        }

        private void ResetOrderBuy()
        {
            gridPrice[3, 5].Value = 0.00;
            gridPrice[4, 5].Value = 0;
            gridPrice[4, 4].Value = 0;

        }

        private void FillOrderSell(OrderInfo a_CurOrder, OrderTable a_CurTable, int a_Remain)
        {
            gridPrice[3, 1].Value = a_CurOrder.Price.ToString("F2");
            gridPrice[4, 1].Value = a_CurOrder.Amount;
            gridPrice[4, 2].Value = a_Remain;

        }
        // 호가 잔량을 채운다.
        private void FillJan()
        {
            if (m_CPDataSet == null)
                return;
            EasyTrader.FutureJpBidTable curTable = m_CPDataSet.GetFutureJpBidTable();
            if (curTable == null)
                return;
            DataRow curRow = curTable.GetLastRow();
            if (curRow == null)
                return;

            object sellVal1 = curRow["매도1우선호가잔량"];
            if (sellVal1 == DBNull.Value)
                return;

            if (centerRow - 4 < 8)
                return;
            if (centerRow + 5 > GlobalVar.ShowMaxPriceNumber - 10)
                return;

            object sellVal2 = curRow["매도2우선호가잔량"];
            object sellVal3 = curRow["매도3우선호가잔량"];
            object sellVal4 = curRow["매도4우선호가잔량"];
            object sellVal5 = curRow["매도5우선호가잔량"];

            object buyVal1 = curRow["매수1우선호가잔량"];
            object buyVal2 = curRow["매수2우선호가잔량"];
            object buyVal3 = curRow["매수3우선호가잔량"];
            object buyVal4 = curRow["매수4우선호가잔량"];
            object buyVal5 = curRow["매수5우선호가잔량"];

            int sumSell = 0, sumBuy = 0;
            gridPrice[centerRow, 2].Value = Convert.ToInt32(sellVal1);
            gridPrice[centerRow - 1, 2].Value = Convert.ToInt32(sellVal2);
            gridPrice[centerRow - 2, 2].Value = Convert.ToInt32(sellVal3);
            gridPrice[centerRow - 3, 2].Value = Convert.ToInt32(sellVal4);
            gridPrice[centerRow - 4, 2].Value = Convert.ToInt32(sellVal5);

            gridPrice[centerRow + 1, 4].Value = Convert.ToInt32(buyVal1);
            gridPrice[centerRow + 2, 4].Value = Convert.ToInt32(buyVal2);
            gridPrice[centerRow + 3, 4].Value = Convert.ToInt32(buyVal3);
            gridPrice[centerRow + 4, 4].Value = Convert.ToInt32(buyVal4);
            gridPrice[centerRow + 5, 4].Value = Convert.ToInt32(buyVal5);


            sumSell = Convert.ToInt32(sellVal1);
            sumSell += Convert.ToInt32(sellVal2);
            sumSell += Convert.ToInt32(sellVal3);
            sumSell += Convert.ToInt32(sellVal4);
            sumSell += Convert.ToInt32(sellVal5);

            sumBuy = Convert.ToInt32(buyVal1);
            sumBuy += Convert.ToInt32(buyVal2);
            sumBuy += Convert.ToInt32(buyVal3);
            sumBuy += Convert.ToInt32(buyVal4);
            sumBuy += Convert.ToInt32(buyVal5);

            SourceGrid.Cells.Views.Cell sellView = new SourceGrid.Cells.Views.Cell();
            sellView.ForeColor = Color.White;
            sellView.BackColor = Color.Blue;
            sellView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            sellView.Font = new Font("굴림", 9, FontStyle.Regular);

            SourceGrid.Cells.Views.Cell buyView = new SourceGrid.Cells.Views.Cell();
            buyView.ForeColor = Color.White;
            buyView.BackColor = Color.Red;
            buyView.TextAlignment = DevAge.Drawing.ContentAlignment.MiddleRight;
            buyView.Font = new Font("굴림", 9, FontStyle.Regular);

            gridPrice[3, 2].Value = sumSell;
            gridPrice[3, 3].Value = sumBuy - sumSell;
            if (sumBuy - sumSell >= 0)
                gridPrice[3, 3].View = buyView;
            else
                gridPrice[3, 3].View = sellView;
            gridPrice[3, 4].Value = sumBuy;


            object totalSell = curRow["매도총호가잔량"];
            object totalBuy = curRow["매수총호가잔량"];
            int dTotalSell = Convert.ToInt32(totalSell);
            int dTotalBuy = Convert.ToInt32(totalBuy);
            gridPrice[2, 2].Value =dTotalSell;
            gridPrice[2, 3].Value = dTotalBuy - dTotalSell;
            if (dTotalBuy - dTotalSell >= 0)
                gridPrice[2, 3].View = buyView;
            else
                gridPrice[2, 3].View = sellView;
            gridPrice[2, 4].Value = dTotalBuy;
        }

        private void comboAccount_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboAccount.SelectedIndex != -1)
            {
                AccountName = comboAccount.SelectedItem.ToString();
                if (m_OrderManager == null)
                    return;
                OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(AccountName);
                ShowOrderPrice(curTable);
            }
        }

        // 이 함수는 주어진 가격으로 위치를 찾는다.
        private int FindValPos(double a_Val)
        {
            for (int r = 5; r < 5 + GlobalVar.ShowMaxPriceNumber; r++)
            {
                for (int c = 0; c < 7; c++)
                {
                    if (c == 3)
                    {
                        object val = gridPrice[r, c].Value;
                        if (Convert.ToDouble(val) == a_Val)
                            return r;
                    }
                }
            }

            return 0;
        }

        // 이 함수는 주문가격이 표시된 셀들을 다시 초기화 한다.
        public void ClearOrderedCell()
        {
            for (int r = 5; r < 5 + GlobalVar.ShowMaxPriceNumber; r++)
            {
                for (int c = 0; c < 7; c++)
                {
                    if (c == 1 || c == 5)
                    {
                        gridPrice[r, c].Value = "";
                        gridPrice[r, c].View = normalView;
                    }
                }
            }

            gridPrice[3, 5].Value = "0";
            gridPrice[4, 5].Value = "0";
            gridPrice[4, 4].Value = "0";

            gridPrice[3, 1].Value = "0";
            gridPrice[4, 1].Value = "0";
            gridPrice[4, 2].Value = "0";
        }

        // 이 함수는 주문가격이 표시된 셀들을 다시 초기화 한다.
        public void ClearBuyOrderCell()
        {
            for (int r = 5; r < 5 + GlobalVar.ShowMaxPriceNumber; r++)
            {
                for (int c = 0; c < 7; c++)
                {
                    if (c == 5)
                    {
                        gridPrice[r, c].Value = "";
                        gridPrice[r, c].View = normalView;
                    }
                }
            }

            gridPrice[3, 5].Value = "0";
            gridPrice[4, 5].Value = "0";
            gridPrice[4, 4].Value = "0";
        }

        public void ClearSellOrderCell()
        {
            for (int r = 5; r < 5 + GlobalVar.ShowMaxPriceNumber; r++)
            {
                for (int c = 0; c < 7; c++)
                {
                    if (c == 1)
                    {
                        gridPrice[r, c].Value = "";
                        gridPrice[r, c].View = normalView;
                    }
                }
            }

            gridPrice[3, 1].Value = "0";
            gridPrice[4, 1].Value = "0";
            gridPrice[4, 2].Value = "0";
        }

        // 이 함수는 손실과 이익에 따라 정해진 손실이나 이익이 있으면 
        // 자동으로 주문을 내준다.
        // 모든 계좌에 대해서 똑같이 청산을 해준다.
        private void SendOrderByLossProfitTick()
        {
            int curTicks = (int)(accProfit / 0.05);
            // 손실에 의한 자동 청산 주문
            if (curTicks < 0 && LossTick != 0 && Math.Abs(curTicks) >= LossTick)
            {
                m_OrderManager.LiquidAll();
            }
            // 이익에 의한 자동 청산 주문
            if (curTicks > 0 && ProfitTick != 0 && curTicks >= ProfitTick)
            {
                m_OrderManager.LiquidAll();
            }
        }

        private void SendOrderByStopValue()
        {
            if (m_OrderManager == null)
                return;
            OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(AccountName);
            if (curTable == null)
                return;

            if (curTable.StopEnabled == true && CurVal == curTable.StopVal)
            {
                m_OrderManager.Liquid(AccountName);
            }
        }

        // 이 함수는 주문가격이 표시된 셀들을 다시 초기화 한다.
        public void ClearStopCell()
        {
            for (int r = 5; r < 5 + GlobalVar.ShowMaxPriceNumber; r++)
            {
                for (int c = 0; c < 7; c++)
                {
                    if (c == 0 || c == 6)
                    {
                        gridPrice[r, c].Value = "";
                        gridPrice[r, c].View = normalView;
                    }
                }
            }

            gridPrice[3, 0].Value = "0";
            gridPrice[3, 6].Value = "0";
        }
        // 이 함수는 스탑 주문의 그리드 위치를 찾아 값을 넣어준다.
        private void ShowStopPrice(OrderTable curTable)
        {
            if (curTable == null)
                return;
            int rowCount = curTable.Rows.Count;
            if (rowCount == 0)
                return;

            DataRow curRow = curTable.Rows[rowCount - 1];
            object remain = curRow["잔고"];
            object remainCode = curRow["잔고구분코드"];
            // 마지막 주문이 잔고 없음 일 때는 
            if (Convert.ToInt32(remain) == 0)
            {
                ClearStopCell();
                m_OrderManager.ClearStopInfo(curTable.TableName);
                return;
            }
            ClearStopCell();
            double stopPrice = curTable.StopVal;
            int valRow = FindValPos(stopPrice);
                    // 값의 범위가 화면 안에 있을 경우
            if (valRow != 0)
            {
                if (curTable.StopOrderType == 1) // 매도일 경우
                {
                    gridPrice[valRow, 6].Value = stopPrice.ToString("F2");
                    gridPrice[valRow, 6].View = stopView;
                }
                else if (curTable.StopOrderType == 2) // 매수일 경우
                {
                    gridPrice[valRow, 0].Value = stopPrice.ToString("F2");
                    gridPrice[valRow, 0].View = stopView;
                }
            }
            if (curTable.StopOrderType == 1) // 매도일 경우
            {
                gridPrice[3, 6].Value = stopPrice.ToString("F2");
            }
            else if (curTable.StopOrderType == 2)
            {
                gridPrice[3, 0].Value = stopPrice.ToString("F2");
            }
        }
        // 이 함수는 주문 번호로 그리드의 위치를 찾아 값을 넣어 준다.
        private void ShowOrderPrice(OrderTable curTable)
        {
            if (curTable == null)
                return;
            int rowCount = curTable.Rows.Count;
            if (rowCount == 0)
                return;

            DataRow curRow = curTable.Rows[rowCount - 1];
            object remain = curRow["잔고"];
            object remainCode = curRow["잔고구분코드"];
            // 마지막 주문이 잔고 없음 일 때는 
            if (Convert.ToInt32(remain) == 0)
            {
                ClearOrderedCell();
                return;
            }

            int lastRemainCode = Convert.ToInt32(remainCode);
            //ClearOrderedCell();
            // 현재 테이블에서 주문 정보 목록을 가져온다.
            PriceOrderList orderList = curTable.OrderList;
            int orderCount = orderList.Count;
            if (orderCount == 0)
                return;

            OrderInfo curOrder = orderList[orderCount - 1];
            double orderPrice = curOrder.Price;
            if (curOrder.RemainCode != 0) // 잔고 없음이 아닐 경우
            {
                int valRow = FindValPos(orderPrice);
                remain = curRow["잔고"];
                // 값의 범위가 화면 안에 있을 경우
                if (valRow != 0)
                {
                    if (curOrder.Order == 1) // 매도일 경우
                    {
                        ClearSellOrderCell();
                        gridPrice[valRow, 1].Value = orderPrice.ToString("F2");
                        gridPrice[valRow, 1].View = orderSellView;
                        if (Convert.ToInt32(remainCode) == 1) // 매도 잔고 있음
                        {
                            FillOrderSell(curOrder, curTable, Convert.ToInt32(remain));
                            accProfit = curTable.CurProfit;
                        }
                    }
                    else if (curOrder.Order == 2) // 매수일 경우
                    {
                        ClearBuyOrderCell();
                        gridPrice[valRow, 5].Value = orderPrice.ToString("F2");
                        gridPrice[valRow, 5].View = orderBuyView;
                        if (Convert.ToInt32(remainCode) == 2) // 매수 잔고 있음
                        {
                            FillOrderBuy(curOrder, curTable, Convert.ToInt32(remain));
                            accProfit = curTable.CurProfit;
                        }
                    }
                }

                /*
                if (Convert.ToInt32(remainCode) == 1) // 매도 잔고 있음
                {
                    FillOrderSell(curOrder, curTable, Convert.ToInt32(remain));
                    accProfit = curTable.CurProfit;
                }
                else if (Convert.ToInt32(remainCode) == 2) // 매수 잔고 있음
                {
                    FillOrderBuy(curOrder, curTable, Convert.ToInt32(remain));
                    accProfit = curTable.CurProfit;
                }*/
            }
            else // 잔고가 없을 경우 모든 값을 지워 준다.
            {
                ClearOrderedCell();
                ResetOrderBuy();
                ResetOrderSell();
                accProfit = 0.0;
            }
        }

        
        // 이 함수는 주문 번호로 그리드의 위치를 찾아 값을 넣어 준다.
        public void ShowOrderPrice(object a_AccountNum)
        {
            if (m_OrderManager == null)
                return;
            OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(a_AccountNum.ToString());
            ShowOrderPrice(curTable);
        }

        // 이 함수는 주문 번호로 그리드의 위치를 찾아 값을 넣어 준다.
        public void ShowOrderPrice(string a_AccountNum)
        {
            if (m_OrderManager == null)
                return;
            OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(a_AccountNum);
            ShowOrderPrice(curTable);
        }

        // 이 함수는 스탑 번호로 그리드의 위치를 찾아 값을 넣어 준다.
        public void ShowStopPrice(object a_AccountNum)
        {
            if (m_OrderManager == null)
                return;
            OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(a_AccountNum.ToString());
            ShowStopPrice(curTable);
        }

        // 이 함수는 Stop 번호로 그리드의 위치를 찾아 값을 넣어 준다.
        public void ShowStopPrice(string a_AccountNum)
        {
            if (m_OrderManager == null)
                return;
            OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(a_AccountNum);
            ShowStopPrice(curTable);
        }

        private void comboOrderType_SelectedIndexChanged(object sender, EventArgs e)
        {
            int iSel = comboOrderType.SelectedIndex;
            if (iSel == 0)
                OrderType = 1;
            else if (iSel == 1)
                OrderType = 2;
            else if (iSel == 2)
                OrderType = 3;
            else if (iSel == 3)
                OrderType = 4;
            else
                OrderType = 2;

            if (OrderType == 1)
            {
                btnCancelFixedOrder.Enabled = true;
            }
            else
            {
                btnCancelFixedOrder.Enabled = false;
            }
        }

        private void comboOrderCond_SelectedIndexChanged(object sender, EventArgs e)
        {
            int iSel = comboOrderCond.SelectedIndex;
            if (iSel == 0)
                OrderCond = 0;
            else if (iSel == 1)
                OrderCond = 1;
            else if (iSel == 2)
                OrderCond = 2;
            else
                OrderCond = 0;
        }

        private void nudLossTicks_ValueChanged(object sender, EventArgs e)
        {
            LossTick = (int)nudLossTicks.Value;
        }

        private void nudProfitTicks_ValueChanged(object sender, EventArgs e)
        {
            ProfitTick = (int)nudProfitTicks.Value;
        }

        private void nudCurValPos_ValueChanged(object sender, EventArgs e)
        {
            centerRow = (int)nudCurValPos.Value;
            if (GridInit)
            {
                ResetPriceGridCellView();
                FillPriceColumn();
                FillJan();
                ShowOrderPrice(AccountName);
                ShowStopPrice(AccountName);
            }
            ShowServerMsg();
            UpdatePrice();
        }

        private void buttonBuy_Click(object sender, EventArgs e)
        {
            if (GlobalVar.AutoOrder == true)
            {
                System.Windows.Forms.MessageBox.Show(GlobalVar.ManualOrderWarnMsg);
                return;
            }
            object a_Market = "1";
            object a_Account = AccountName;
            object a_ItemCode = FutureCode;
            object a_Amount = gridAmount[1, 0].Value;
            object a_OrderPrice = CurVal;
            object a_BuySell = 2;
            object a_OrderType = OrderType;
            object a_OrderCond = OrderCond;
            
            // 주문유형이 시장가 일 때
            if (OrderType == 2)
            {
                a_OrderPrice = 0;
                m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
            }
            else // 주문 유형이 시장가가 아닐 때
            {
                m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
            }

            string orderInfo = "수동매수 주문 정보 ->";
            orderInfo += "주문계좌 : " + a_Account + ", ";
            orderInfo += "주문시간 : " + GlobalVar.TimeToInt().ToString() + ", ";
            orderInfo += "주문유형 : " + a_BuySell.ToString() + ", ";
            orderInfo += "주문가격 : " + a_OrderPrice.ToString() + ", ";
            orderInfo += "주문수량 : " + a_Amount.ToString();
            GlobalVar.WriteLog(orderInfo);
        }

        private void buttonSell_Click(object sender, EventArgs e)
        {
            if (GlobalVar.AutoOrder == true)
            {
                System.Windows.Forms.MessageBox.Show(GlobalVar.ManualOrderWarnMsg);
                return;
            }
            object a_Market = "1";
            object a_Account = AccountName;
            object a_ItemCode = FutureCode;
            object a_Amount = gridAmount[1, 0].Value;
            object a_OrderPrice = CurVal;
            object a_BuySell = 1;
            object a_OrderType = OrderType;
            object a_OrderCond = OrderCond;

            // 주문유형이 시장가 일 때
            if (OrderType == 2)
            {
                a_OrderPrice = 0;
                m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
            }
            else // 주문 유형이 시장가가 아닐 때
            {
                m_OrderManager.SendNormalOrder(a_Market, a_Account, a_ItemCode, a_Amount, a_OrderPrice, a_BuySell, a_OrderType, a_OrderCond);
            }

            string orderInfo = "수동매도 주문 정보 ->";
            orderInfo += "주문계좌 : " + a_Account + ", ";
            orderInfo += "주문시간 : " + GlobalVar.TimeToInt().ToString() + ", ";
            orderInfo += "주문유형 : " + a_BuySell.ToString() + ", ";
            orderInfo += "주문가격 : " + a_OrderPrice.ToString() + ", ";
            orderInfo += "주문수량 : " + a_Amount.ToString();
            GlobalVar.WriteLog(orderInfo);
        }

        private void buttonLiquidAll_Click(object sender, EventArgs e)
        {
            GlobalVar.WriteLog("주문창에서 모두 청산을 부름");
            if (m_OrderManager == null)
                return;
            // 모두 청산 함수를 부른다.
            m_OrderManager.LiquidAll();
        }

        // 현재 지정된 지정가를 모두 취소한다.
        // 현재 테이블만 가능하다.
        private void btnCancelFixedOrder_Click(object sender, EventArgs e)
        {
            // 현재 계좌를 찾아 온다.
            if (m_OrderManager == null)
                return;
            OrderTable curTable = m_OrderManager.OrderDataSet.GetOrderTable(AccountName);
            if (curTable == null)
                return;
            if (curTable.FixedBuyOrderEnable == true)
            {
                curTable.FixedBuyOrderEnable = false;
                curTable.FixedBuyOrderVal = 0.00;
                ClearBuyOrderCell();
            }
            if (curTable.FixedSellOrderEnable == true)
            {
                curTable.FixedSellOrderEnable = false;
                curTable.FixedSellOrderVal = 0.00;
                ClearSellOrderCell();
            }
        }
    }
}
